package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.IUserRedisService;
import cn.wolfcode.luowowo.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前置拦截器
 */
@Component
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserRedisService userRedisService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            //如果贴了这个注解
            if (hm.hasMethodAnnotation(RequireLogin.class)) {
                //获取令牌
                String token = request.getHeader("token");
                UserInfo userInfo = userRedisService.getUserByToken(token);
                if (userInfo == null) {
                    //前后端分离的话只能用这种方式到前端页面
                    response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                    return false;
                }
            }
        }
        return true;
    }
}
